<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理 - 仓库管理系统</title>
    <link rel="stylesheet" href="https://unpkg.com/layui@2.8.18/dist/css/layui.css">
    <style>
        body {
            background-color: #f2f2f2;
            margin: 0;
            padding: 0;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .header h1 {
            margin: 0;
            font-size: 24px;
            font-weight: 300;
        }

        .main-container {
            display: flex;
            height: calc(100vh - 70px);
        }

        .sidebar {
            width: 250px;
            background-color: #fff;
            box-shadow: 2px 0 4px rgba(0,0,0,0.1);
            overflow-y: auto;
        }

        .content {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
        }

        .nav-item {
            padding: 15px 20px;
            border-bottom: 1px solid #f0f0f0;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
        }

        .nav-item:hover {
            background-color: #f8f9fa;
            color: #667eea;
        }

        .nav-item.active {
            background-color: #667eea;
            color: white;
        }

        .nav-item i {
            margin-right: 10px;
            font-size: 16px;
        }

        .nav-item span {
            font-size: 14px;
        }

        .dashboard {
            background: white;
            border-radius: 8px;
            padding: 30px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }

        .dashboard h2 {
            color: #333;
            margin-bottom: 30px;
            font-weight: 300;
            border-bottom: 2px solid #667eea;
            padding-bottom: 10px;
        }

        .toolbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            flex-wrap: wrap;
            gap: 10px;
        }

        .search-box {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }

        .search-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: #667eea;
            color: white;
        }

        .btn-primary:hover {
            background-color: #5a6fd8;
        }

        .btn-success {
            background-color: #52c41a;
            color: white;
        }

        .btn-success:hover {
            background-color: #49aa15;
        }

        .btn-warning {
            background-color: #faad14;
            color: white;
        }

        .btn-warning:hover {
            background-color: #d48806;
        }

        .btn-danger {
            background-color: #ff4d4f;
            color: white;
        }

        .btn-danger:hover {
            background-color: #cf1322;
        }

        .product-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .product-table th,
        .product-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .product-table th {
            background-color: #fafafa;
            font-weight: 500;
            color: #333;
        }

        .product-table tr:hover {
            background-color: #f8f9fa;
        }

        .stock-normal {
            color: #52c41a;
            font-weight: 500;
        }

        .stock-low {
            color: #faad14;
            font-weight: 500;
        }

        .stock-out {
            color: #ff4d4f;
            font-weight: 500;
        }

        .action-buttons {
            display: flex;
            gap: 5px;
        }

        .btn-sm {
            padding: 4px 8px;
            font-size: 12px;
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 30px;
            border-radius: 8px;
            width: 80%;
            max-width: 700px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #f0f0f0;
        }

        .modal-title {
            font-size: 18px;
            font-weight: 500;
            color: #333;
        }

        .close {
            font-size: 24px;
            font-weight: bold;
            cursor: pointer;
            color: #999;
        }

        .close:hover {
            color: #333;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }

        .form-input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            box-sizing: border-box;
        }

        .form-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .form-textarea {
            resize: vertical;
            min-height: 80px;
        }

        .form-row {
            display: flex;
            gap: 15px;
        }

        .form-col {
            flex: 1;
        }

        .form-actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 30px;
        }

        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
            gap: 8px;
            align-items: center;
        }

        .pagination button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            background: white;
            cursor: pointer;
            border-radius: 4px;
            font-size: 14px;
            transition: all 0.3s ease;
            min-width: 40px;
        }

        .pagination button:hover {
            background-color: #f8f9fa;
            border-color: #667eea;
        }

        .pagination button.active {
            background-color: #667eea;
            color: white;
            border-color: #667eea;
        }

        .pagination button:disabled {
            background-color: #f5f5f5;
            color: #ccc;
            cursor: not-allowed;
            border-color: #ddd;
        }

        .loading {
            text-align: center;
            padding: 50px;
            color: #999;
        }

        .no-data {
            text-align: center;
            padding: 50px;
            color: #999;
        }

        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .stat-card h3 {
            margin: 0 0 10px 0;
            font-size: 28px;
            font-weight: 300;
        }

        .stat-card p {
            margin: 0;
            font-size: 14px;
            opacity: 0.9;
        }

        .box-display {
            font-weight: 500;
            color: #667eea;
        }

        .stock-info {
            display: flex;
            flex-direction: column;
            gap: 2px;
        }

        .stock-quantity {
            font-weight: 500;
        }

        .stock-box {
            font-size: 12px;
            color: #666;
        }
    </style>
</head>
<body>
<!-- 头部 -->
<div class="header">
    <h1><i class="layui-icon layui-icon-cart"></i> 商品管理</h1>
</div>

<!-- 主容器 -->
<div class="main-container">
    <!-- 左侧导航栏 -->
    <div class="sidebar">
        <div class="nav-item" onclick="goToHome()">
            <i class="layui-icon layui-icon-home"></i>
            <span>系统首页</span>
        </div>
        <div class="nav-item" onclick="goToCustomers()">
            <i class="layui-icon layui-icon-user"></i>
            <span>客户管理</span>
        </div>
        <div class="nav-item active" onclick="showProducts()">
            <i class="layui-icon layui-icon-cart"></i>
            <span>商品管理</span>
        </div>
        <div class="nav-item" onclick="goToCategories()">
            <i class="layui-icon layui-icon-tabs"></i>
            <span>分类管理</span>
        </div>
        <div class="nav-item" onclick="goToOrders()">
            <i class="layui-icon layui-icon-form"></i>
            <span>订单管理</span>
        </div>
        <div class="nav-item" onclick="goToStockIn()">
            <i class="layui-icon layui-icon-add-1"></i>
            <span>入库管理</span>
        </div>
        <div class="nav-item" onclick="goToStockOut()">
            <i class="layui-icon layui-icon-delete"></i>
            <span>出库管理</span>
        </div>
        <div class="nav-item" onclick="goToReports()">
            <i class="layui-icon layui-icon-chart"></i>
            <span>统计报表</span>
        </div>
        <div class="nav-item" onclick="goToSettings()">
            <i class="layui-icon layui-icon-set"></i>
            <span>系统设置</span>
        </div>
    </div>

    <!-- 主内容区域 -->
    <div class="content">
        <div class="dashboard">
            <h2><i class="layui-icon layui-icon-cart"></i> 商品管理</h2>

            <!-- 统计卡片 -->
            <div class="stats-cards">
                <div class="stat-card">
                    <h3 id="totalProducts">0</h3>
                    <p>商品总数</p>
                </div>
                <div class="stat-card">
                    <h3 id="lowStockProducts">0</h3>
                    <p>低库存商品</p>
                </div>
                <div class="stat-card">
                    <h3 id="outOfStockProducts">0</h3>
                    <p>缺货商品</p>
                </div>
            </div>

            <!-- 工具栏 -->
            <div class="toolbar">
                <div class="search-box">
                    <input type="text" id="searchName" class="search-input" placeholder="按商品名称搜索">
                    <select id="categoryFilter" class="search-input" style="width: auto;" onchange="filterByCategory()">
                        <option value="">所有分类</option>
                    </select>
                    <button class="btn btn-primary" onclick="searchProducts()">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button class="btn btn-success" onclick="resetSearch()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                    <button class="btn btn-warning" onclick="showLowStockProducts()">
                        <i class="layui-icon layui-icon-exclamation"></i> 低库存
                    </button>
                    <select id="pageSizeSelect" class="search-input" style="width: auto;" onchange="changePageSize()">
                        <option value="10">每页10条</option>
                        <option value="20">每页20条</option>
                        <option value="50">每页50条</option>
                        <option value="100">每页100条</option>
                    </select>
                </div>
                <button class="btn btn-primary" onclick="showAddProductModal()">
                    <i class="layui-icon layui-icon-add-1"></i> 添加商品
                </button>
            </div>

            <!-- 商品列表 -->
            <div id="productList">
                <div class="loading">
                    <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                    <p>加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑商品模态框 -->
<div id="productModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title" id="modalTitle">添加商品</h3>
            <span class="close" onclick="closeProductModal()">&times;</span>
        </div>
        <form id="productForm">
            <input type="hidden" id="productId">
            <div class="form-row">
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">商品名称 *</label>
                        <input type="text" id="productName" class="form-input" required>
                    </div>
                </div>
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">商品分类</label>
                        <select id="category" class="form-input" required>
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="form-row">
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">规格</label>
                        <input type="text" id="specification" class="form-input" placeholder="如：500ml、1kg等">
                    </div>
                </div>
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">单位</label>
                        <input type="text" id="unit" class="form-input" placeholder="如：瓶、个、包等">
                    </div>
                </div>
            </div>
            <div class="form-row">
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">单价</label>
                        <input type="number" id="price" class="form-input" step="0.01" min="0" placeholder="0.00">
                    </div>
                </div>
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">最低库存</label>
                        <input type="number" id="minStock" class="form-input" min="0" value="0">
                    </div>
                </div>
            </div>
            <div class="form-row">
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">一箱包含数量</label>
                        <input type="number" id="boxQuantity" class="form-input" min="1" value="1">
                    </div>
                </div>
                <div class="form-col">
                    <div class="form-group">
                        <label class="form-label">箱单位</label>
                        <input type="text" id="boxUnit" class="form-input" value="箱" placeholder="如：箱、盒、包等">
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="form-label">初始库存</label>
                <input type="number" id="stockQuantity" class="form-input" min="0" value="0">
            </div>
            <div class="form-actions">
                <button type="button" class="btn" onclick="closeProductModal()">取消</button>
                <button type="submit" class="btn btn-primary">保存</button>
            </div>
        </form>
    </div>
</div>

<!-- 库存调整模态框 -->
<div id="stockModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 class="modal-title">调整库存</h3>
            <span class="close" onclick="closeStockModal()">&times;</span>
        </div>
        <form id="stockForm">
            <input type="hidden" id="stockProductId">
            <div class="form-group">
                <label class="form-label">商品名称</label>
                <input type="text" id="stockProductName" class="form-input" readonly>
            </div>
            <div class="form-group">
                <label class="form-label">当前库存</label>
                <input type="text" id="currentStock" class="form-input" readonly>
            </div>
            <div class="form-group">
                <label class="form-label">调整数量</label>
                <input type="number" id="adjustQuantity" class="form-input" required>
                <small style="color: #666;">正数为增加，负数为减少</small>
            </div>
            <div class="form-actions">
                <button type="button" class="btn" onclick="closeStockModal()">取消</button>
                <button type="submit" class="btn btn-primary">确认调整</button>
            </div>
        </form>
    </div>
</div>

<script src="https://unpkg.com/layui@2.8.18/dist/layui.js"></script>
<script>
    let products = [];
    let currentPage = 1;
    let pageSize = 10;
    let categories = new Set();

    // 页面加载完成后执行
    layui.use(['layer'], function(){
        var layer = layui.layer;
        loadProducts();
        loadProductStats();
        loadCategories();
    });

    // 箱数量转换工具函数
    function formatBoxQuantity(totalQuantity, boxQuantity, boxUnit, unit) {
        if (boxQuantity <= 0 || !boxQuantity) {
            return totalQuantity + (unit || '');
        }

        const boxes = Math.floor(totalQuantity / boxQuantity);
        const remaining = totalQuantity % boxQuantity;

        let result = '';
        if (boxes > 0) {
            result += boxes + (boxUnit || '箱');
        }
        if (remaining > 0) {
            if (boxes > 0) {
                result += remaining + (unit || '');
            } else {
                result += remaining + (unit || '');
            }
        }

        return result || '0' + (unit || '');
    }

    // 获取库存状态样式
    function getStockStatusClass(stockQuantity, minStock) {
        if (stockQuantity <= 0) {
            return 'stock-out';
        } else if (stockQuantity <= minStock) {
            return 'stock-low';
        } else {
            return 'stock-normal';
        }
    }

    // 获取库存状态文本
    function getStockStatusText(stockQuantity, minStock) {
        if (stockQuantity <= 0) {
            return '缺货';
        } else if (stockQuantity <= minStock) {
            return '低库存';
        } else {
            return '正常';
        }
    }

    // 加载商品统计数据
    function loadProductStats() {
        // 加载商品总数
        fetch('/api/products')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    document.getElementById('totalProducts').textContent = data.data.length;
                }
            })
            .catch(error => console.error('加载商品总数失败:', error));

        // 加载低库存商品数
        fetch('/api/products/low-stock')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    document.getElementById('lowStockProducts').textContent = data.data.length;
                }
            })
            .catch(error => console.error('加载低库存商品数失败:', error));

        // 计算缺货商品数
        fetch('/api/products')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const outOfStock = data.data.filter(p => p.stockQuantity <= 0).length;
                    document.getElementById('outOfStockProducts').textContent = outOfStock;
                }
            })
            .catch(error => console.error('计算缺货商品数失败:', error));
    }

    // 加载分类数据
    function loadCategories() {
        fetch('/api/categories/enabled')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    const categories = data.data;
                    
                    // 更新筛选下拉框
                    const categoryFilter = document.getElementById('categoryFilter');
                    categoryFilter.innerHTML = '<option value="">所有分类</option>';
                    categories.forEach(category => {
                        categoryFilter.innerHTML += `<option value="${category.categoryName}">${category.categoryName}</option>`;
                    });
                    
                    // 更新添加/编辑表单中的分类下拉框
                    const categorySelect = document.getElementById('category');
                    categorySelect.innerHTML = '<option value="">请选择分类</option>';
                    categories.forEach(category => {
                        categorySelect.innerHTML += `<option value="${category.categoryName}">${category.categoryName}</option>`;
                    });
                }
            })
            .catch(error => console.error('加载分类数据失败:', error));
    }

    // 加载商品列表
    function loadProducts() {
        const productList = document.getElementById('productList');
        productList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>加载中...</p></div>';

        fetch('/api/products/with-box-display')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    products = data.data;
                    // 收集所有分类
                    categories.clear();
                    products.forEach(product => {
                        if (product.category) {
                            categories.add(product.category);
                        }
                    });
                    updateCategoryFilter();
                    renderProductTable();
                } else {
                    productList.innerHTML = '<div class="no-data">加载失败: ' + data.message + '</div>';
                }
            })
            .catch(error => {
                console.error('加载商品列表失败:', error);
                productList.innerHTML = '<div class="no-data">加载失败，请检查网络连接</div>';
            });
    }

    // 更新分类过滤器
    function updateCategoryFilter() {
        const categoryFilter = document.getElementById('categoryFilter');
        const currentValue = categoryFilter.value;

        // 清空现有选项（保留"所有分类"）
        categoryFilter.innerHTML = '<option value="">所有分类</option>';

        // 添加分类选项
        Array.from(categories).sort().forEach(category => {
            const option = document.createElement('option');
            option.value = category;
            option.textContent = category;
            categoryFilter.appendChild(option);
        });

        // 恢复之前的选择
        categoryFilter.value = currentValue;
    }

    // 渲染商品表格
    function renderProductTable() {
        const productList = document.getElementById('productList');

        if (products.length === 0) {
            productList.innerHTML = '<div class="no-data">暂无商品数据</div>';
            return;
        }

        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = startIndex + pageSize;
        const pageProducts = products.slice(startIndex, endIndex);

        let tableHTML = `
                <table class="product-table">
                    <thead>
                        <tr>
                            <th>商品名称</th>
                            <th>分类</th>
                            <th>规格</th>
                            <th>单价</th>
                            <th>库存</th>
                            <th>箱显示</th>
                            <th>状态</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;

        pageProducts.forEach(product => {
            const stockStatusClass = getStockStatusClass(product.stockQuantity, product.minStock);
            const stockStatusText = getStockStatusText(product.stockQuantity, product.minStock);
            const boxDisplay = formatBoxQuantity(product.stockQuantity, product.boxQuantity, product.boxUnit, product.unit);
            const createdTime = new Date(product.createdTime).toLocaleString('zh-CN');
            const price = product.price ? '¥' + product.price.toFixed(2) : '-';

            tableHTML += `
                    <tr>
                        <td>${product.productName || '-'}</td>
                        <td>${product.category || '-'}</td>
                        <td>${product.specification || '-'}</td>
                        <td>${price}</td>
                        <td>
                            <div class="stock-info">
                                <span class="stock-quantity">${product.stockQuantity || 0}${product.unit || ''}</span>
                                <span class="stock-box box-display">${boxDisplay}</span>
                            </div>
                        </td>
                        <td class="box-display">${boxDisplay}</td>
                        <td><span class="${stockStatusClass}">${stockStatusText}</span></td>
                        <td>${createdTime}</td>
                        <td>
                            <div class="action-buttons">
                                <button class="btn btn-warning btn-sm" onclick="editProduct(${product.id})">
                                    <i class="layui-icon layui-icon-edit"></i>
                                </button>
                                <button class="btn btn-success btn-sm" onclick="adjustStock(${product.id})">
                                    <i class="layui-icon layui-icon-add-1"></i>
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="deleteProduct(${product.id})">
                                    <i class="layui-icon layui-icon-delete"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
        });

        tableHTML += `
                    </tbody>
                </table>
            `;

        // 添加分页信息
        const totalPages = Math.ceil(products.length / pageSize);
        const startRecord = startIndex + 1;
        const endRecord = Math.min(endIndex, products.length);

        // 显示分页信息
        tableHTML += `
                <div style="margin-top: 20px; display: flex; justify-content: space-between; align-items: center; color: #666; font-size: 14px;">
                    <div>显示第 ${startRecord} - ${endRecord} 条，共 ${products.length} 条记录</div>
                    <div>每页 ${pageSize} 条</div>
                </div>
            `;

        // 添加分页控件
        if (totalPages > 1) {
            tableHTML += '<div class="pagination">';

            // 上一页按钮
            if (currentPage > 1) {
                tableHTML += `<button onclick="goToPage(${currentPage - 1})">上一页</button>`;
            }

            // 页码按钮
            const startPage = Math.max(1, currentPage - 2);
            const endPage = Math.min(totalPages, currentPage + 2);

            for (let i = startPage; i <= endPage; i++) {
                const activeClass = i === currentPage ? 'active' : '';
                tableHTML += `<button class="${activeClass}" onclick="goToPage(${i})">${i}</button>`;
            }

            // 下一页按钮
            if (currentPage < totalPages) {
                tableHTML += `<button onclick="goToPage(${currentPage + 1})">下一页</button>`;
            }

            tableHTML += '</div>';
        } else {
            // 即使只有一页也显示分页信息
            tableHTML += '<div class="pagination">';
            tableHTML += '<button class="active" disabled>1</button>';
            tableHTML += '</div>';
        }

        productList.innerHTML = tableHTML;
    }

    // 搜索商品
    function searchProducts() {
        const name = document.getElementById('searchName').value.trim();

        if (!name) {
            loadProducts();
            return;
        }

        const productList = document.getElementById('productList');
        productList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>搜索中...</p></div>';

        fetch(`/api/products/search?productName=${encodeURIComponent(name)}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    products = data.data;
                    currentPage = 1;
                    renderProductTable();
                } else {
                    productList.innerHTML = '<div class="no-data">搜索失败: ' + data.message + '</div>';
                }
            })
            .catch(error => {
                console.error('搜索商品失败:', error);
                productList.innerHTML = '<div class="no-data">搜索失败，请检查网络连接</div>';
            });
    }

    // 按分类筛选
    function filterByCategory() {
        const category = document.getElementById('categoryFilter').value;

        if (!category) {
            loadProducts();
            return;
        }

        const productList = document.getElementById('productList');
        productList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>加载中...</p></div>';

        fetch(`/api/products/category/${encodeURIComponent(category)}`)
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    products = data.data;
                    currentPage = 1;
                    renderProductTable();
                } else {
                    productList.innerHTML = '<div class="no-data">筛选失败: ' + data.message + '</div>';
                }
            })
            .catch(error => {
                console.error('按分类筛选失败:', error);
                productList.innerHTML = '<div class="no-data">筛选失败，请检查网络连接</div>';
            });
    }

    // 显示低库存商品
    function showLowStockProducts() {
        const productList = document.getElementById('productList');
        productList.innerHTML = '<div class="loading"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i><p>加载中...</p></div>';

        fetch('/api/products/low-stock')
            .then(response => response.json())
            .then(data => {
                if (data.code === 200) {
                    products = data.data;
                    currentPage = 1;
                    renderProductTable();
                } else {
                    productList.innerHTML = '<div class="no-data">加载失败: ' + data.message + '</div>';
                }
            })
            .catch(error => {
                console.error('加载低库存商品失败:', error);
                productList.innerHTML = '<div class="no-data">加载失败，请检查网络连接</div>';
            });
    }

    // 重置搜索
    function resetSearch() {
        document.getElementById('searchName').value = '';
        document.getElementById('categoryFilter').value = '';
        loadProducts();
    }

    // 显示添加商品模态框
    function showAddProductModal() {
        document.getElementById('modalTitle').textContent = '添加商品';
        document.getElementById('productForm').reset();
        document.getElementById('productId').value = '';
        
        // 确保分类下拉框重置为默认选项
        const categorySelect = document.getElementById('category');
        categorySelect.value = '';
        
        document.getElementById('productModal').style.display = 'block';
    }

    // 编辑商品
    function editProduct(id) {
        const product = products.find(p => p.id === id);
        if (!product) return;

        document.getElementById('modalTitle').textContent = '编辑商品';
        document.getElementById('productId').value = product.id;
        document.getElementById('productName').value = product.productName || '';
        document.getElementById('specification').value = product.specification || '';
        document.getElementById('unit').value = product.unit || '';
        document.getElementById('price').value = product.price || '';
        document.getElementById('stockQuantity').value = product.stockQuantity || 0;
        document.getElementById('minStock').value = product.minStock || 0;
        document.getElementById('boxQuantity').value = product.boxQuantity || 1;
        document.getElementById('boxUnit').value = product.boxUnit || '箱';

        // 设置分类下拉框的值
        const categorySelect = document.getElementById('category');
        categorySelect.value = product.category || '';

        document.getElementById('productModal').style.display = 'block';
    }

    // 更新库存
    function updateStock(id) {
        const product = products.find(p => p.id === id);
        if (!product) return;

        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.prompt({
                title: '更新库存',
                value: product.stockQuantity,
                formType: 0
            }, function(value, index) {
                const newQuantity = parseInt(value);
                if (isNaN(newQuantity) || newQuantity < 0) {
                    layer.msg('请输入有效的库存数量', {icon: 2});
                    return;
                }

                fetch(`/api/products/${id}/stock?quantity=${newQuantity}`, {
                    method: 'PUT'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        layer.msg('库存更新成功', {icon: 1});
                        loadProducts();
                        loadProductStats();
                    } else {
                        layer.msg('库存更新失败: ' + data.message, {icon: 2});
                    }
                })
                .catch(error => {
                    console.error('更新库存失败:', error);
                    layer.msg('库存更新失败，请检查网络连接', {icon: 2});
                });
                layer.close(index);
            });
        });
    }

    // 关闭模态框
    function closeProductModal() {
        document.getElementById('productModal').style.display = 'none';
    }

    // 删除商品
    function deleteProduct(id) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.confirm('确定要删除这个商品吗？', {
                title: '确认删除',
                btn: ['确定', '取消']
            }, function(index) {
                fetch(`/api/products/${id}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        layer.msg('删除成功', {icon: 1});
                        loadProducts();
                        loadProductStats();
                    } else {
                        layer.msg('删除失败: ' + data.message, {icon: 2});
                    }
                })
                .catch(error => {
                    console.error('删除商品失败:', error);
                    layer.msg('删除失败，请检查网络连接', {icon: 2});
                });
                layer.close(index);
            });
        });
    }

    // 分页
    function goToPage(page) {
        currentPage = page;
        renderProductTable();
    }

    // 改变每页显示条数
    function changePageSize() {
        const newPageSize = parseInt(document.getElementById('pageSizeSelect').value);
        pageSize = newPageSize;
        currentPage = 1; // 重置到第一页
        renderProductTable();
    }

    // 表单提交
    document.getElementById('productForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const productId = document.getElementById('productId').value;
        const productData = {
            productName: document.getElementById('productName').value,
            specification: document.getElementById('specification').value,
            category: document.getElementById('category').value,
            unit: document.getElementById('unit').value,
            price: parseFloat(document.getElementById('price').value) || 0,
            stockQuantity: parseInt(document.getElementById('stockQuantity').value) || 0,
            minStock: parseInt(document.getElementById('minStock').value) || 0,
            boxQuantity: parseInt(document.getElementById('boxQuantity').value) || 1,
            boxUnit: document.getElementById('boxUnit').value
        };

        const url = productId ? `/api/products/${productId}` : '/api/products';
        const method = productId ? 'PUT' : 'POST';

        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(productData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                layui.use(['layer'], function(){
                    var layer = layui.layer;
                    layer.msg(productId ? '更新成功' : '添加成功', {icon: 1});
                });
                closeProductModal();
                loadProducts();
                loadProductStats();
            } else {
                layui.use(['layer'], function(){
                    var layer = layui.layer;
                    layer.msg('操作失败: ' + data.message, {icon: 2});
                });
            }
        })
        .catch(error => {
            console.error('保存商品失败:', error);
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg('保存失败，请检查网络连接', {icon: 2});
            });
        });
    });

    // 导航函数
    function goToHome() {
        window.location.href = 'index.html';
    }

    function goToCustomers() {
        window.location.href = 'customers.html';
    }



    function showProducts() {
        // 当前页面，无需跳转
    }
    // 跳转到分类管理页面
    function goToCategories() {
        window.location.href = 'categories.html';
    }

    function goToOrders() {
        // 跳转到订单管理页面
        window.location.href = 'orders.html';
    }

    function goToStockIn() {
        // 跳转到入库管理页面
        alert('入库管理功能开发中...');
    }

    function goToStockOut() {
        // 跳转到出库管理页面
        alert('出库管理功能开发中...');
    }

    function goToReports() {
        // 跳转到统计报表页面
        alert('统计报表功能开发中...');
    }

    function goToSettings() {
        // 跳转到系统设置页面
        alert('系统设置功能开发中...');
    }

    // 点击模态框外部关闭
    window.onclick = function(event) {
        const modal = document.getElementById('productModal');
        if (event.target === modal) {
            closeProductModal();
        }
    }
</script>
</body>
</html>